<template>
  <div>
    <div class="box">
      <ConButton
        :multipleSelection="multipleSelection"
        :continerState="state"
        @setListLog='setListLog'
      ></ConButton>
      <div class="serch">
        <SerchInput
          :serchdata="tableData"
          v-if="tableData.length > 0"
          @serchActive="serchActive"
        ></SerchInput>
      </div>
      <div class="tableborder">
        <el-table
          ref="multipleTable"
          :data="AfterChangeData"
          tooltip-effect="dark"
          style="width: calc(100% - 2px); margin: 1px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column class="fontcolor" :label="$t('Container_Name')">
            <template slot-scope="scope">
              <router-link
                tag="span"
                :to="'/Container/ConContent/' + scope.row.Id"
                class="fontcolor"
                >{{ scope.row.Names[0] }}</router-link
              >
            </template>
          </el-table-column>
          <el-table-column :label="$t('Container_Status')">
            <template slot-scope="scope">
              <el-button
                @click="changeState(scope.row)"
                size="mini"
                :type="scope.row.State | containerStateStyle"
                >{{ $t( 'Container_'+ ((scope.row.State==='running'||scope.row.State==='paused')?scope.row.State:'exited' ))}}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            :label="$t('Container_Monitor')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div>
                <img
                  style="cursor: pointer"
                  class="imgSize"
                  :title="$t('Container_Log')"
                  src="../../public/image/log.svg"
                  alt=""
                  @click="toLink(`/Container/Logs/${scope.row.Id}`)"
                />
                <img
                  style="cursor: pointer"
                  class="imgSize"
                  :title="$t('Container_Check')"
                  src="../../public/image/content.svg"
                  alt=""
                  @click="toLink(`/Container/CheckContainer/${scope.row.Id}`)"
                />
                <img
                  style="cursor: pointer"
                  v-if="scope.row.State === 'running'"
                  class="imgSize"
                  :title="$t('Container_Statistic')"
                  src="../../public/image/cuont.svg"
                  alt=""
                  @click="toLink(`/Container/CountContainer/${scope.row.Id}`)"
                />
                <img
                  style="cursor: pointer"
                  v-if="scope.row.State === 'running'"
                  class="imgSize"
                  :title="$t('Container_Console')"
                  src="../../public/image/cmd.svg"
                  alt=""
                  @click="toLink(`/Container/ConsoleContainer/${scope.row.Id}`)"
                />
                <!-- <i style="cursor:pointer;" class="iconfont icon-wulianwang-" title="日志" @click="toLink(`/Container/Logs/${scope.row.Id}`)"></i>
              <i style="cursor:pointer;" class="iconfont icon-gengduo" title="检查" @click="toLink(`/Container/CheckContainer/${scope.row.Id}`)"></i>
              <i style="cursor:pointer;" v-if="scope.row.State === 'running'" class="iconfont icon-zhenduan" title="统计资料" @click="toLink(`/Container/CountContainer/${scope.row.Id}`)"></i>
              <i style="cursor:pointer;" v-if="scope.row.State === 'running'" class="iconfont icon-minglinghang" title="执行控制台" @click="toLink(`/Container/ConsoleContainer/${scope.row.Id}`)"></i> -->
              </div>
              <p style="font-size: 12px">
                {{ $t("Container_Log") }} {{ $t("Container_Check") }}
                {{ $t("Container_Statistic") }} {{ $t("Container_Console") }}
              </p>
            </template>
          </el-table-column>
          <el-table-column :label="$t('Container_Image')" show-overflow-tooltip>
            <template slot-scope="scope">
              <router-link
                tag="span"
                :to="'/Image/ImageContent/' + scope.row.ImageID"
                class="fontcolor"
                >{{ scope.row.Image }}</router-link
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="Created"
            :label="$t('Container_CreateTime')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">{{
              scope.row.Created | createdData
            }}</template>
          </el-table-column>
          <el-table-column :label="$t('Container_IP')" show-overflow-tooltip>
            <template slot-scope="scope">{{
              scope.row | filterNetworks
            }}</template>
          </el-table-column>
          <el-table-column
            prop="Ports[1].PrivatePort"
            :label="$t('Container_PublishPort')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <a
                @click="linkPort(item)"
                class="fontcolor"
                v-for="(item, index) in Portshtml(scope.row)"
                :key="index"
                >{{ item }}</a
              >
              <p style="font-size: 12px">{{ $t("Container_Jump") }}</p>
            </template>
          </el-table-column>
          <!-- <el-table-column
          prop="Ports[1].PrivatePort"
          label="发布端口"
          show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.Ports | Ports(scope.row)}}</template>
        </el-table-column> -->
        </el-table>
      </div>
      <div class="page">
        <div class="pagenum">
          <el-select
            v-model="pageNum"
            placeholder="请选择活动区域"
            style="width: 80px"
            size="mini"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="item in Math.ceil(
                (serchdata ? serchdata.length : tableData.length) / pageSize
              )"
              :key="item"
            ></el-option>
          </el-select>
          {{ $t("Container_Page") }}
        </div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="serchdata ? serchdata.length : tableData.length"
        >
        </el-pagination>
      </div>
    </div>
    <div v-show='list[0]' class="tips">
      <el-alert v-for="(item,index) in list" :key="index" :title="item.title" :type="item.type" effect="light" :closable='false'> </el-alert>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Button,
  Table,
  TableColumn,
  Select,
  Pagination,
  Input,
  Option,
  alert,
} from "element-ui";
import post from "@/utils/post";
import ConButton from "@/components/container/ConButton";
import SerchInput from "@/components/container/SerchInput";
Vue.use(Button);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Select);
Vue.use(Pagination);
Vue.use(Input);
Vue.use(Option);
Vue.use(alert);

export default {
  data() {
    return {
      serchdata: null, // 搜索筛选后的数据
      tableData: [], // 容器数据
      multipleSelection: [], // 选择的容器数据
      pageNum: 1, // 当前页
      pageSize: 6, // 每页显示数量
      state: [], // 容器状态，数组最后一个值为1时，表示要停止容器，为2时，表示要恢复暂停的容器，为3时，要启动容器。
      list: [], //容器操作日志，当前页面存在，跳转不保存 [{type:类型,title:提示文字}]
    };
  },
  mounted() {
    // 进入页面获取容器数据
    this.fetchContainer();
  },
  computed: {
    // 返回当前页面显示的数据
    AfterChangeData() {
      let start = (this.pageNum - 1) * this.pageSize;
      let end = this.pageNum * this.pageSize;
      return this.serchdata
        ? this.serchdata.slice(start, end)
        : this.tableData.slice(start, end);
    },
  },
  methods: {
    // 端口跳转页面
    linkPort(port) {
      if (port !== "." && port.indexOf(":") !== -1) {
        let ip = "";
        if (localStorage.getItem("baseURL")) {
          ip = localStorage.getItem("baseURL").split(":")[1].replace("//", "");
        }
        window.open(
          "http://" +
            (localStorage.getItem("baseURL") ? ip : location.hostname) +
            ":" +
            port.split(" : ")[0]
        );
      }
    },
    // 处理端口
    Portshtml(item) {
      const value = item.Ports;
      if (value.length === 0) {
        return "...";
      } else {
        
         let arr = value.map((item) => {
          if (item.PublicPort) {
            return `${item.PublicPort} : ${item.PrivatePort} `;
          } else {
            return item.PrivatePort + " ";
          }
        });
        return  arr
      }
    },
    // 点击状态，改变容器当前状态
    changeState(item) {
      if (item.State === "running") {
        if (!confirm("确认暂停容器？")) {
          return;
        }
        this.state.push(1);
        this.multipleSelection = [item];
      } else{
         this.state.push(2);
         this.multipleSelection = [item];
      }
      // else if (item.State === "exited") {
      //   this.state.push(2);
      //   this.multipleSelection = [item];
      // }
    },
    // 搜索框激活,接受搜索组件传回来的值
    serchActive(arr) {
      this.serchdata = arr;
    },
    // 跳转页面
    toLink(path) {
      this.$router.push(path);
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // 当前页数改变
    handleCurrentChange(val) {
      this.pageNum = val;
    },
    // 获取容器列表数据
    fetchContainer() {
      const docker =
        'curl --unix-socket /var/run/docker.sock -s "http:/v1.40/containers/json?all=true"'; // 查询
      post(
        { docker },
        (res) => {
          this.tableData = res;
        },
        this
      );
    },
    // 处理点击选框事件
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 处理table选中，element自带函数
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 添加日志数据
    setListLog(item) {
      this.list.unshift(item)
    },
  },
  components: {
    ConButton,
    SerchInput,
  },
  filters: {
    // 处理ip地址
    filterNetworks: (value) => {
      let mode = value.HostConfig.NetworkMode;
      if (mode === "default") {
        mode = "bridge";
      }
      if (JSON.stringify(value.NetworkSettings.Networks) === "{}") {
        return "...";
      }
      if (value.NetworkSettings.Networks[mode].IPAddress) {
        return value.NetworkSettings.Networks[mode].IPAddress;
      } else {
        return "...";
      }
    },
    // 显示状态的颜色
    containerStateStyle: (value) => {
      if (value === "running") {
        return "success";
      } else if (value === "paused") {
        return "warning";
      } else {
        return "danger";
      }
    },
    // 处理时间戳
    createdData: (value) => {
      let date = new Date(value * 1000);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    // 处理端口显示
    // Ports: (value, item) => {
    //   console.log(value, item)
    //   if (value.length === 0) {
    //     return '...'
    //   } else {
    //     return value.map(item => {
    //       if (item.PublicPort) {
    //         return `${item.PublicPort} : ${item.PrivatePort}`
    //       } else {
    //         return item.PrivatePort
    //       }
    //     }).join(' , ')
    //   }
    // }
  },
  watch: {
    // 监听是否需要重新获取容器信息
    "$store.state.isFetchContainer": function (newdata, olddata) {
      if (newdata) {
        this.fetchContainer();
        this.multipleSelection = [];
        this.$store.commit("changeIsFetchContainer", false);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  font-size: 12px;
}
.imgSize {
  width: 18px;
  margin: 0px 4.2px;
}
.serch {
  margin-top: 30px;
}
.tableborder {
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-top: 30px;
}
.page {
  margin-top: 30px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  line-height: 28px;
  .pagenum {
    margin-right: 10px;
  }
}
.iconfont {
  font-size: 20px;
  color: #067fb5;
}
.fontcolor {
  color: #067fb5;
  cursor: pointer; // 鼠标移上去变小手
}
.tips{
  padding: 20px;
  &>div{
    margin: 10px 0;
  }
}
</style>
